package cn.lili.modules.union.serviceimpl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.lili.common.enums.ResultCode;
import cn.lili.common.event.TransactionCommitSendMQEvent;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.security.enums.SceneEnums;
import cn.lili.common.utils.SnowFlake;
import cn.lili.common.utils.StringUtils;
import cn.lili.common.vo.PageVO;
import cn.lili.exchange.AmqpExchangeProperties;
import cn.lili.modules.member.client.UserClient;
import cn.lili.modules.member.entity.dos.Union;
import cn.lili.modules.member.entity.dos.UnionLog;
import cn.lili.modules.member.entity.dos.UnionMember;
import cn.lili.modules.member.entity.dos.User;
import cn.lili.modules.member.entity.dto.UnionAddDTO;
import cn.lili.modules.member.service.UserService;
import cn.lili.modules.operationcenter.client.OperationCenterClient;
import cn.lili.modules.operationcenter.entity.dos.OperationCenter;
import cn.lili.modules.order.order.client.OrderClient;
import cn.lili.modules.order.order.entity.dos.OrderFlow;
import cn.lili.modules.order.order.entity.vo.OrderVO;
import cn.lili.modules.order.order.entity.vo.PerformanceDetailVO;
import cn.lili.modules.order.order.entity.vo.UnionMonthFundsVO;
import cn.lili.modules.order.order.entity.vo.UnionOrderParams;
import cn.lili.modules.promotion.client.GreenClient;
import cn.lili.modules.system.client.IRegionClient;
import cn.lili.modules.system.entity.dos.Region;
import cn.lili.modules.union.mapper.UnionMapper;
import cn.lili.modules.union.service.UnionMemberService;
import cn.lili.modules.union.service.UnionService;
import cn.lili.mybatis.util.PageUtil;
import cn.lili.routing.UnionRoutingKey;
import cn.wildfirechat.pojos.OutputCreateGroupResult;
import cn.wildfirechat.pojos.PojoGroupInfo;
import cn.wildfirechat.sdk.GroupAdmin;
import cn.wildfirechat.sdk.model.IMResult;
import com.alibaba.fastjson.JSONObject;
import com.api.UserApi;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pojos.OpenAppUser;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.apache.shardingsphere.transaction.annotation.ShardingTransactionType;
import org.apache.shardingsphere.transaction.core.TransactionType;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Slf4j
public class UnionServiceImpl extends ServiceImpl<UnionMapper, Union> implements UnionService {

    private final UserService userService;

    private final ApplicationEventPublisher applicationEventPublisher;

    private final AmqpExchangeProperties amqpExchangeProperties;

    private final UnionMemberService unionMemberService;

    private final OrderClient orderClient;

    private final UserApi userApi;

    private final OperationCenterClient operationCenterClient;

    private final UserClient userClient;

    private final GreenClient greenClient;

    /**
     * 分页查询工会列表
     * @param union
     * @param pageVO
     * @return
     */
    @Override
    public Page<Union> getByPage (Union union, PageVO pageVO) {
        /*LambdaQueryWrapper<Union> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(union.getUnionName()), Union::getUnionName, union.getUnionName());
        queryWrapper.like(StringUtils.isNotEmpty(union.getChairmanName()), Union::getChairmanName, union.getChairmanName());
        queryWrapper.eq(StringUtils.isNotEmpty(union.getChairmanId()), Union::getChairmanId, union.getChairmanId());
        queryWrapper.eq(StringUtils.isNotEmpty(union.getCityId()), Union::getCityId, union.getCityId());
        queryWrapper.eq(Union::getDeleteFlag, false);
        if (SceneEnums.OPERATION_CENTER.name().equals(Objects.requireNonNull(UserContext.getCurrentUser()).getScene().name())) {
            OperationCenter operationCenter = operationCenterClient.getOperationCenter(Objects.requireNonNull(UserContext.getCurrentUser()).getId());
            if (null != operationCenter && StringUtils.isNotEmpty(operationCenter.getProvinceId())) {
                queryWrapper.eq(Union::getProvinceId, operationCenter.getProvinceId());
            }
        }else {
            queryWrapper.eq(StringUtils.isNotEmpty(union.getProvinceId()), Union::getProvinceId, union.getProvinceId());
        }*/
        if (SceneEnums.OPERATION_CENTER.name().equals(Objects.requireNonNull(UserContext.getCurrentUser()).getScene().name())) {
            OperationCenter operationCenter = operationCenterClient.getOperationCenter(Objects.requireNonNull(UserContext.getCurrentUser()).getId());
            if (null != operationCenter && StringUtils.isNotEmpty(operationCenter.getProvinceId())) {
                union.setProvinceId(operationCenter.getProvinceId());
            }
        }
        Page<Union> page = this.baseMapper.getByPage(PageUtil.initPage(pageVO), union);
        if (!page.getRecords().isEmpty()) {
            page.getRecords().forEach(union1 -> {
                // 工会人数
                long count = unionMemberService.getCountByUnionId(union1.getId());
                union1.setMemberCount(count);

                // 工会经费
                String areaId = union1.getProvinceId() + "," + union1.getCityId();
                Double greenScore = orderClient.getMonthUnionGreenScoreByAreaId(areaId);
                union1.setCurrentMonthMoney(greenScore == null ? 0D : greenScore);

                // 工会会长ID和昵称从fy获取
                /*User user = userClient.getById(union1.getChairmanId());
                if (null != user) {
                    union1.setChairmanId(user.getAccount());
                    union1.setChairmanName(user.getFyName());
                }*/
            });
        }
        return page;
    }


    /**
     * 分页查询工会列表
     * @param union
     * @param pageVO
     * @return
     */
    @Override
    public Page<Union> searchByPage (Union union, PageVO pageVO) {
        LambdaQueryWrapper<Union> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(union.getUnionName()), Union::getUnionName, union.getUnionName());
        queryWrapper.eq(StringUtils.isNotEmpty(union.getProvinceId()), Union::getProvinceId, union.getProvinceId());
        queryWrapper.eq(StringUtils.isNotEmpty(union.getCityName()), Union::getCityName, union.getCityName());
        queryWrapper.eq(Union::getDeleteFlag, false);
        queryWrapper.orderByAsc(Union::getUnionName);
        Page<Union> page = this.page(PageUtil.initPage(pageVO), queryWrapper);
        if (!page.getRecords().isEmpty()) {
            //取proviceId
            List<String> provinceIdList = page.getRecords().stream().map(item->item.getProvinceId()).distinct().collect(Collectors.toList());
            //查询省份id所在的运营中心
            Map<String, String> operationCenterMap = null;
            if (CollUtil.isNotEmpty(provinceIdList)) {
                List<OperationCenter> operationCenters = operationCenterClient.getOperationCenterListByProviceIds(provinceIdList);
                if (CollUtil.isNotEmpty(operationCenters)) {
//                    log.info("#searchByPage# 参数:{},查询的运营中心结果:{}", JSONObject.toJSONString(provinceIdList), JSONObject.toJSONString(operationCenters));
                    operationCenterMap = operationCenters.stream()
                            .collect(Collectors.toMap(OperationCenter::getProvinceId, OperationCenter::getOperationName, (existing, replacement) -> existing));
                }
            }


            List<String> chairmanIdList = page.getRecords().stream().map(item->item.getChairmanId()).collect(Collectors.toList());
            List<User> userList = userService.findByIdList(chairmanIdList);

            page.getRecords().forEach(union1 -> {
                // 工会人数
                long count = unionMemberService.getCountByUnionId(union1.getId());
                union1.setMemberCount(count);

                User chairman = userList.stream().filter(item->item.getId().equals(union1.getChairmanId())).findFirst().orElse(null);
                if(null!=chairman){
                    union1.setChairmanName(chairman.getNickName());
                    union1.setChairmanPortrait(chairman.getFace());
                }
            });

            //获取工会所在的运营中心名称
            if (CollUtil.isNotEmpty(operationCenterMap)) {
                for (Union union1 : page.getRecords()) {
                    union1.setOperationCenterName(StrUtil.isNotEmpty(operationCenterMap.get(union1.getProvinceId())) ? operationCenterMap.get(union1.getProvinceId()) : "");
                }
            }
        }
        return page;
    }


    /**
     * 添加工会
     * @param unionAddDTO
     */
    @Override
    @Transactional
    @ShardingTransactionType(TransactionType.BASE)
    public void add (UnionAddDTO unionAddDTO) {
        if (StringUtils.isEmpty(unionAddDTO.getUnionName())
                || StringUtils.isEmpty(unionAddDTO.getCityId())
                || StringUtils.isEmpty(unionAddDTO.getChairmanId())) {
            throw new ServiceException(ResultCode.PARAMS_ERROR);
        }

        if (SceneEnums.OPERATION_CENTER.name().equals(UserContext.getCurrentUser().getScene().name())) {
            OperationCenter operationCenter = operationCenterClient.getOperationCenter(UserContext.getCurrentUser().getId());
            if (null != operationCenter) {
                unionAddDTO.setProvinceId(operationCenter.getProvinceId());
            }else {
                throw new ServiceException("运营中心数据异常");
            }
        }else {
            if (StringUtils.isEmpty(unionAddDTO.getProvinceId())) {
                throw new ServiceException(ResultCode.PARAMS_ERROR);
            }
        }

        Union union = getByArea(unionAddDTO.getProvinceId(), unionAddDTO.getCityId());
        if (null != union) {
            throw new ServiceException("工会所属城市已存在");
        }

        Union unionChairMan = getByMemberId(unionAddDTO.getChairmanId());
        if (null != unionChairMan) {
            throw new ServiceException("用户已是其他工会会长");
        }

        UnionMember unionMember = unionMemberService.getByUnionMemberId(unionAddDTO.getChairmanId());
        if (null != unionMember) {
            throw new ServiceException("用户已是其他工会成员");
        }

        User user = userService.getById(unionAddDTO.getChairmanId());
        Union saveUnion = new Union(unionAddDTO);
        saveUnion.setFirstChairmanId(unionAddDTO.getChairmanId());
        if (StringUtils.isEmpty(unionAddDTO.getChairmanName())) {
            unionAddDTO.setChairmanName(user.getUsername());
        }
        saveUnion.setChairmanName(unionAddDTO.getChairmanName());
        saveUnion.setFirstChairmanName(unionAddDTO.getChairmanName());
        saveUnion.setId(SnowFlake.getIdStr());
        if (null != user && StringUtils.isNotEmpty(user.getOpenId())) {
            try {
                // 创建群组
                OpenAppUser openAppUser = userApi.getUserinfoByOpenId(user.getOpenId());
                PojoGroupInfo pojoGroupInfo = new PojoGroupInfo();
                pojoGroupInfo.setType(1);
                pojoGroupInfo.setName(unionAddDTO.getUnionName());
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("unionId", saveUnion.getId());
                jsonObject.put("unionUrl", "");
                pojoGroupInfo.setExtra(jsonObject.toJSONString());

                IMResult<OutputCreateGroupResult> group = GroupAdmin.createGroup(openAppUser.getUId(), pojoGroupInfo, new ArrayList<>(), new ArrayList<Integer>() {{
                    add(0);
                }}, null);
                if(group.code != 0) {
                    log.error("群组创建失败：{}", group.msg);
                }
                saveUnion.setGroupId(group.result.getGroup_id());
            }catch (Exception e) {
                log.error("创建群组异常：{}", e.getMessage());
            }
        }
        if (this.save(saveUnion)) {
            UnionLog unionLog = UnionLog.builder()
                    .operationRemark("创建工会:" + unionAddDTO.getUnionName())
                    .createTime(new Date())
                    .unionId(saveUnion.getId())
                    .operationUserId(UserContext.getCurrentId())
                    .operationUserName(Objects.requireNonNull(UserContext.getCurrentUser()).getUsername())
                    .build();

            applicationEventPublisher.publishEvent(
                    TransactionCommitSendMQEvent.builder()
                            .source("UNION_LOG")
                            .exchange(amqpExchangeProperties.getUnion())
                            .routingKey(UnionRoutingKey.ADD_UNION_LOG)
                            .message(unionLog)
                            .build());


            // 工会成员
            unionMemberService.addUnionMember(unionAddDTO, saveUnion.getId());
        }
    }


    /**
     * 变更会长
     * @param unionParams
     */
    @Override
    public void updateChairman (Union unionParams) {
        // 查询用户是否是会长
        Union checkChairMan = getByMemberId(unionParams.getChairmanId());
        if (null != checkChairMan && !checkChairMan.getId().equals(unionParams.getId())) {
            throw new ServiceException("用户已是其他工会会长");
        }

        UnionMember unionMember = unionMemberService.getByUnionMemberId(unionParams.getChairmanId());
        if (null != unionMember) {
            throw new ServiceException("用户已是其他工会成员");
        }

        Union union = this.getById(unionParams.getId());
        if (union.getDeleteFlag()) {
            throw new ServiceException("工会已解散");
        }

        // 查询用户工会
        User user = userService.getById(unionParams.getChairmanId());
        // 用户已加入工会，但不是当前变更会长的工会
        if (null != user
                && StringUtils.isNotEmpty(user.getUnionId())
                && !user.getUnionId().equals(union.getId())) {
            throw new ServiceException("用户已加入其他工会，请先退出工会");
        }

        List<UnionLog> unionLogList = Lists.newArrayList();
        assert user != null;
        if (StringUtils.isEmpty(unionParams.getChairmanName())) {
            unionParams.setChairmanName(user.getUsername());
        }
        UnionLog unionLog = UnionLog.builder()
                .operationRemark("工会会长由" + union.getChairmanName() + "变更为" + unionParams.getChairmanName())
                .createTime(new Date())
                .id(SnowFlake.getIdStr())
                .operationUserId(UserContext.getCurrentId())
                .operationUserName(Objects.requireNonNull(UserContext.getCurrentUser()).getUsername())
                .build();
        unionLogList.add(unionLog);

        UnionLog unionLog2 = UnionLog.builder()
                .operationRemark("会长变更，原会长" + union.getChairmanName() + "自动退出工会")
                .createTime(new Date())
                .unionId(unionParams.getId())
                .operationUserId(UserContext.getCurrentId())
                .operationUserName(Objects.requireNonNull(UserContext.getCurrentUser()).getUsername())
                .build();
        unionLogList.add(unionLog2);


        // 变更群主
        try {
            User oldUser = userService.getById(union.getChairmanId());
            if (null != oldUser && StringUtils.isNotEmpty(oldUser.getOpenId())) {
                OpenAppUser openAppUser = userApi.getUserinfoByOpenId(oldUser.getOpenId());
                if (null != openAppUser) {
                    User newUser = userService.getById(unionParams.getChairmanId());
                    OpenAppUser nUser = userApi.getUserinfoByOpenId(newUser.getOpenId());
                    GroupAdmin.transferGroup(openAppUser.getUId(), union.getGroupId(), nUser.getUId(), new ArrayList<Integer>() {{
                        add(0);
                    }}, null);
                }
            }
        }catch (Exception e) {
            log.error("变更群主异常：{}", e.getMessage());
        }

        union.setChairmanId(unionParams.getChairmanId());
        union.setChairmanName(StringUtils.isEmpty(unionParams.getChairmanName()) ? user.getUsername() : unionParams.getChairmanName());
        this.updateById(union);

        if (!unionLogList.isEmpty()) {
            applicationEventPublisher.publishEvent(
                    TransactionCommitSendMQEvent.builder()
                            .source("UNION_LOG")
                            .exchange(amqpExchangeProperties.getUnion())
                            .routingKey(UnionRoutingKey.BATCH_ADD_UNION_LOG)
                            .message(unionLogList)
                            .build());
        }

    }

    /**
     * 根据省市查询工会
     * @param provinceId
     * @param cityId
     * @return
     */
    public Union getByArea (String provinceId, String cityId) {
        LambdaQueryWrapper<Union> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotEmpty(provinceId), Union::getProvinceId, provinceId);
        queryWrapper.eq(StringUtils.isNotEmpty(cityId), Union::getCityId, cityId);
        queryWrapper.last("limit 1");
        return this.getOne(queryWrapper);
    }

    /**
     * 根据用户ID查询用户是否是会长
     * @param memberId
     * @return
     */
    public Union getByMemberId (String memberId) {
        LambdaQueryWrapper<Union> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Union::getChairmanId, memberId);
        queryWrapper.last("limit 1");
        return this.getOne(queryWrapper);
    }

    /**
     * 解散群
     * @param unionId
     */
    @Override
    public void deleteUnion (String unionId) {
        if (StringUtils.isEmpty(unionId)) {
            throw new ServiceException(ResultCode.PARAMS_ERROR);
        }

        Union union = this.getById(unionId);
        if (union.getDeleteFlag()) {
            throw new ServiceException("工会已解散");
        }

        //union.setDeleteFlag(Boolean.TRUE);
        LambdaUpdateWrapper<Union> unionLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        unionLambdaUpdateWrapper.eq(Union::getId, unionId);
        unionLambdaUpdateWrapper.set(Union::getDeleteFlag, true);
        if (this.update(unionLambdaUpdateWrapper)) {
            // 解除工会和成员绑定关系
            LambdaUpdateWrapper<UnionMember> memberLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            memberLambdaUpdateWrapper.eq(UnionMember::getUnionId, unionId);
            memberLambdaUpdateWrapper.set(UnionMember::getDeleteFlag, true);
            unionMemberService.update(memberLambdaUpdateWrapper);

            // 解除用户绑定工会关系
            LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(User::getUnionId, unionId);
            updateWrapper.set(User::getUnionId, null);
            userService.update(updateWrapper);

            // 解散群
            try {
                User user = userService.getById(union.getChairmanId());
                if (null != user && StringUtils.isNotEmpty(user.getOpenId())) {
                    OpenAppUser openAppUser = userApi.getUserinfoByOpenId(user.getOpenId());
                    if (null != openAppUser) {
                        GroupAdmin.dismissGroup(openAppUser.getUId(), union.getGroupId(), new ArrayList<Integer>() {{
                            add(0);
                        }}, null);
                    }
                }
            }catch (Exception e) {
                log.error("解散群异常：{}", e.getMessage());
            }
        }
    }

    /**
     * 修改工会信息
     */
    @Override
    public void updateUnion (Union unionParam) {
        if (StringUtils.isEmpty(unionParam.getId())) {
            throw new ServiceException(ResultCode.PARAMS_ERROR);
        }
        Union union = this.getById(unionParam.getId());
        List<UnionLog> unionLogList = Lists.newArrayList();
        // 判断修改工会城市
        if (StringUtils.isNotEmpty(unionParam.getProvinceId()) && StringUtils.isNotEmpty(unionParam.getCityId())) {
            if (!unionParam.getProvinceId().equals(union.getProvinceId()) || !unionParam.getCityId().equals(union.getCityId())) {
                if (getByArea(unionParam.getProvinceId(), unionParam.getCityId()) != null) {
                    throw new ServiceException("工会所属城市已存在");
                }
                UnionLog unionLog = UnionLog.builder()
                        .operationRemark("工会城市由" + union.getProvinceName() + "-" + union.getCityName()
                                + "变更为" + unionParam.getProvinceName() + "-" + unionParam.getCityName())
                        .createTime(new Date())
                        .unionId(unionParam.getId())
                        .operationUserId(UserContext.getCurrentId())
                        .operationUserName(Objects.requireNonNull(UserContext.getCurrentUser()).getUsername())
                        .build();
                unionLogList.add(unionLog);
            }
        }
        if (StringUtils.isNotEmpty(unionParam.getUnionName()) && !unionParam.getUnionName().equals(union.getUnionName())) {
            UnionLog unionLog = UnionLog.builder()
                    .operationRemark("工会名称由" + union.getUnionName()
                            + "变更为" + unionParam.getUnionName())
                    .createTime(new Date())
                    .unionId(unionParam.getId())
                    .operationUserId(UserContext.getCurrentId())
                    .operationUserName(Objects.requireNonNull(UserContext.getCurrentUser()).getUsername())
                    .build();
            unionLogList.add(unionLog);

            // 修改群名称
            try {
                User user = userService.getById(union.getChairmanId());
                if (null != user && StringUtils.isNotEmpty(user.getOpenId())) {
                    OpenAppUser openAppUser = userApi.getUserinfoByOpenId(user.getOpenId());
                    if (null != openAppUser) {
                        GroupAdmin.modifyGroupInfo(openAppUser.getUId(), union.getGroupId(), 0, unionParam.getUnionName(), new ArrayList<Integer>() {{
                            add(0);
                        }}, null);
                    }
                }
            }catch (Exception e) {
                log.error("修改群名称异常：{}", e.getMessage());
            }
        }

        if (StringUtils.isNotEmpty(unionParam.getChairmanId()) && !unionParam.getChairmanId().equals(union.getChairmanId())) {
            updateChairman(unionParam);
        }
        this.updateById(unionParam);

        if (!unionLogList.isEmpty()) {
            applicationEventPublisher.publishEvent(
                    TransactionCommitSendMQEvent.builder()
                            .source("UNION_LOG")
                            .exchange(amqpExchangeProperties.getUnion())
                            .routingKey(UnionRoutingKey.BATCH_ADD_UNION_LOG)
                            .message(unionLogList)
                            .build());
        }
    }

    /**
     * 根据ID获取工会信息
     * @param id
     * @return
     */
    @Override
    public Union getUnionById (String id) {
        if (StringUtils.isEmpty(id)) {
            throw new ServiceException(ResultCode.PARAMS_ERROR);
        }
        Union union = this.getById(id);
        long count = unionMemberService.getCountByUnionId(id);
        union.setMemberCount(count);

        String areaId = union.getProvinceId() + "," + union.getCityId();
        Double greenScore = orderClient.getMonthUnionGreenScoreByAreaId(areaId);
        union.setCurrentMonthMoney(greenScore);

        User user = userClient.getById(union.getFirstChairmanId());
        if (null != user) {
            union.setFirstChairmanId(user.getAccount());
            union.setFirstChairmanName(user.getFyName());
        }
        return union;
    }

    @Override
    public OrderVO todayFirstOrder(String unionId) {
        Union union = this.baseMapper.selectById(unionId);

        List<UnionMember> memberList = unionMemberService.getMemberIdList(unionId);
        if(null==memberList || memberList.isEmpty()){
            return null;
        }

        OrderVO order = null;
        if(null == union){
            throw new ServiceException(ResultCode.PARAMS_ERROR);
        }

        List<String> memberIdList = memberList.stream().map(item->item.getMemberId()).collect(Collectors.toList());
        OrderVO orderVO = orderClient.todayOrderForUnionV2(memberIdList);
        if(null!=orderVO){
            order = new OrderVO();
            order.setOrderItems(orderVO.getOrderItems());
            String buyerId = orderVO.getBuyerId(); //购买人ID
            User user = userService.getById(buyerId);
            order.setBuyerName(user.getNickName());
            order.setBuyerPortrait(user.getFace());
        }
        return order;
    }

    @Override
    public Page<OrderVO> todayOrderByPage(String unionId,Integer pageNo,Integer pageSize) {
        Union union = this.baseMapper.selectById(unionId);
        if(null == union){
            throw new ServiceException(ResultCode.PARAMS_ERROR);
        }
        List<UnionMember> memberList = unionMemberService.getMemberIdList(unionId);
        if(null==memberList || memberList.isEmpty()){
            return null;
        }

        List<String> memberIdList = memberList.stream().map(item->item.getMemberId()).collect(Collectors.toList());

        Page<OrderVO> orderVOPage = orderClient.getOrderForUnionByPageV2(memberIdList,pageNo,pageSize);
        if(null!=orderVOPage){
            List<OrderVO> dataList = new ArrayList<>();
            orderVOPage.getRecords().forEach(orderVO -> {
                OrderVO order = new OrderVO();
                order.setOrderItems(orderVO.getOrderItems());
                String buyerId = orderVO.getBuyerId(); //购买人ID
                User user = userService.getById(buyerId);
                order.setBuyerName(user.getFyName());
                order.setBuyerPortrait(user.getFace());
                dataList.add(order);
            });
            orderVOPage.setRecords(dataList);
        }
        return orderVOPage;
    }

    /**
     * 工会经费详情
     * @return
     */
    @Override
    public Page<OrderFlow> getUnionMoneyDetail (UnionOrderParams params) {
        if (StringUtils.isNotEmpty(params.getUnionId())) {
            Union union = this.getById(params.getUnionId());
            params.setRegionId(union.getProvinceId() + "," + union.getCityId());
            params.setProvinceId(union.getProvinceId());
            return orderClient.getUnionMoneyDetail(params);
        }
        return null;
    }

    /**
     * 获取工会已结算，待结算，已退单金额
     * @return
     */
    @Override
    public PerformanceDetailVO getUnionMoneyStatisticsDetail (UnionOrderParams params) {
        if (StringUtils.isNotEmpty(params.getUnionId())) {
            Union union = this.getById(params.getUnionId());
            params.setRegionId(union.getProvinceId() + "," + union.getCityId());
            PerformanceDetailVO performanceDetailVO = orderClient.getUnionMoneyStatisticsDetail(params);
            if (null == performanceDetailVO) {
                return new PerformanceDetailVO();
            }{
                return performanceDetailVO;
            }
        }
        return new PerformanceDetailVO();
    }

    /**
     * 分页查询工会经费发放记录
     * @param unionId
     * @return
     */
    @Override
    public Page<UnionMonthFundsVO> getUnionFundsByPage (String unionId) {
        if (StringUtils.isNotEmpty(unionId)) {
            UnionOrderParams params = new UnionOrderParams();

            Union union = this.getById(unionId);
            params.setRegionId(union.getProvinceId() + "," + union.getCityId());
            params.setProvinceId(union.getProvinceId());
            params.setUnionId(unionId);
            //return orderClient.getUnionCommissByMonth(params);
            return greenClient.getSumContributeSettleByUnion(params);
        }
        return null;
    }

    /**
     * 获取工会本月分销订单数量、已完成订单数量、未完成订单数量、已退单数量
     * @param unionId
     * @return
     */
    @Override
    public PerformanceDetailVO getCurrentOrderCount (String unionId) {
        if (StringUtils.isNotEmpty(unionId)) {
            UnionOrderParams params = new UnionOrderParams();
            Union union = this.getById(unionId);
            params.setRegionId(union.getProvinceId() + "," + union.getCityId());
            return orderClient.getCurrentMonthUnionOrderCountByUnion(params.getRegionId());
        }
        return new PerformanceDetailVO();
    }

    /**
     * 获取工会上月分销订单数量、已完成订单数量、未完成订单数量、已退单数量
     * @param unionId
     * @return
     */
    @Override
    public PerformanceDetailVO getLastOrderCount (String unionId) {
        if (StringUtils.isNotEmpty(unionId)) {
            UnionOrderParams params = new UnionOrderParams();
            Union union = this.getById(unionId);
            params.setRegionId(union.getProvinceId() + "," + union.getCityId());
            return orderClient.getLastMonthUnionOrderByUnion(params.getRegionId());
        }
        return new PerformanceDetailVO();
    }

    /**
     * 获取工会城市列表
     * @return
     */
    @Override
    public List<Union> getCityListByProvinceId () {
        LambdaQueryWrapper<Union> queryWrapper = new LambdaQueryWrapper<>();
        if (SceneEnums.OPERATION_CENTER.name().equals(UserContext.getCurrentUser().getScene().name())) {
            OperationCenter operationCenter = operationCenterClient.getOperationCenter(UserContext.getCurrentUser().getId());
            if (null != operationCenter) {
                queryWrapper.eq(Union::getProvinceId, operationCenter.getProvinceId());
            }
        }
        return this.list(queryWrapper);
    }

}
